package com.baselibrary.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.baselibrary.R;
import com.baselibrary.bean.SharePosterBean;
import com.baselibrary.view.VipHeardImgView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


/**
 * description:
 */
public class PosterStyle extends LinearLayout {
    public static final int POSTER_STYLE_ONE = 0;
    public static final int POSTER_STYLE_TWO = 1;
    public static final int POSTER_STYLE_THREE = 2;
    private final String TAG = "DrawLongPictureUtil";
    private Context context;
    private Listener listener;
    private SharePosterBean shareInfo;
    private int styleType;

    private View rootView;
    private LinearLayout llTopView;
    private LinearLayout llContent;
    private LinearLayout llBottomView;

    private ImageView ivPlay;

    private VipHeardImgView imgUserIcon;
    private ImageView shareImage;
    private TextView tvUserName;
    private TextView tvContent;

    // 长图的宽度，默认为屏幕宽度
    private int longPictureWidth;
    // 最终压缩后的长图宽度
    private int finalCompressLongPictureWidth;
    // 长图两边的间距
    private int picMargin;

    private int widthTop = 0;
    private int heightTop = 0;

    private int widthContent = 0;
    private int heightContent = 0;

    private int widthBottom = 0;
    private int heightBottom = 0;

    public PosterStyle(Context context, SharePosterBean sharePosterBean, int styleType, Listener listener) {
        super(context);
        this.listener = listener;
        init(context, sharePosterBean, styleType);
    }

    public void removeListener() {
        this.listener = null;
    }

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    private void init(Context context, SharePosterBean sharePosterBean, int styleType) {
        this.context = context;
        this.shareInfo = sharePosterBean;
        this.styleType = styleType;
        longPictureWidth = ScreenUtils.getScreenWidth(context);
        picMargin = 0;

        if (styleType == POSTER_STYLE_ONE) {
            rootView = LayoutInflater.from(context).inflate(R.layout.layout_draw_canvas_one, this, false);
        } else if (styleType == POSTER_STYLE_TWO) {
            rootView = LayoutInflater.from(context).inflate(R.layout.layout_draw_canvas_two, this, false);
        } else if (styleType == POSTER_STYLE_THREE) {
            rootView = LayoutInflater.from(context).inflate(R.layout.layout_draw_canvas_three, this, false);
        }
        initView();
    }

    private void initView() {
        llTopView = rootView.findViewById(R.id.ll_top_view);

        imgUserIcon = rootView.findViewById(R.id.civ_avatar);
        shareImage = rootView.findViewById(R.id.iv_share_img);
        tvUserName = rootView.findViewById(R.id.tv_user_name);
        tvContent = rootView.findViewById(R.id.tv_share_content);

        ivPlay = rootView.findViewById(R.id.iv_play);

        llContent = rootView.findViewById(R.id.ll_content);
        llBottomView = rootView.findViewById(R.id.ll_bottom_view);

        layoutView(llTopView);
        layoutView(llBottomView);

        widthTop = llTopView.getMeasuredWidth();
        heightTop = llTopView.getMeasuredHeight();

        widthBottom = llBottomView.getMeasuredWidth();
        heightBottom = llBottomView.getMeasuredHeight();

        Log.d(TAG, "drawLongPicture layout top view = " + widthTop + " × " + heightTop);
        Log.d(TAG, "drawLongPicture layout llContent view = " + widthContent + " × " + heightContent);
        Log.d(TAG, "drawLongPicture layout bottom view = " + widthBottom + " × " + heightBottom);
    }

    /**
     * 手动测量view宽高
     */
    private void layoutView(View v) {
        int width = ScreenUtils.getScreenWidth(context);
        int height = ScreenUtils.getScreenHeight(context);

        v.layout(0, 0, width, height);
        int measuredWidth = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
        int measuredHeight = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        v.measure(measuredWidth, measuredHeight);
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
    }

    public void startDraw() {
        // 需要先下载全部需要用到的图片（用户头像、图片等），下载完成后再进行长图的绘制操作
        downloadAllImage();
    }

    private void downloadAllImage() {
        Glide.with(context).asBitmap().load(shareInfo.userAvatar).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                imgUserIcon.setData(resource, shareInfo.isFans, View.GONE);
//                imgUserIcon.setImageBitmap(resource);
                Glide.with(context).asBitmap().load(shareInfo.shareImage).into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        shareImage.setImageBitmap(resource);
                        draw();
                    }
                });
            }
        });
    }

    private Bitmap getLinearLayoutBitmap(LinearLayout linearLayout, int w, int h) {
        Bitmap originBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(originBitmap);
        linearLayout.draw(canvas);
        return ImageUtil.resizeImage(originBitmap, longPictureWidth, h);
    }

    private void draw() {
        tvUserName.setText(shareInfo.userName);
        if (TextUtils.isEmpty(shareInfo.shareContent)) {
            shareInfo.shareContent = "发布了一条动态";
        }
        tvContent.setText(shareInfo.shareContent);

        ivPlay.setVisibility(shareInfo.isVideo ? View.VISIBLE : View.GONE);

        // 计算出最终生成的长图的高度 = 上、中、图片总高度、下等个个部分加起来
        int allBitmapHeight = heightTop + heightContent + heightBottom;

        // 创建空白画布
        Bitmap.Config config = Bitmap.Config.ARGB_8888;
        Bitmap bitmapAll;
        try {
            bitmapAll = Bitmap.createBitmap(longPictureWidth, allBitmapHeight, config);
        } catch (Exception e) {
            e.printStackTrace();
            config = Bitmap.Config.RGB_565;
            bitmapAll = Bitmap.createBitmap(longPictureWidth, allBitmapHeight, config);
        }
        Canvas canvas = new Canvas(bitmapAll);
        canvas.drawColor(Color.WHITE);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setFilterBitmap(true);

        // 绘制top view
        canvas.drawBitmap(getLinearLayoutBitmap(llTopView, widthTop, heightTop), 0, 0, paint);
        canvas.save();

        // 绘制content view
//        canvas.translate(ScreenUtils.dip2px(context, 20), heightTop);
//        staticLayout.draw(canvas);

        // 绘制图片view
        canvas.restore();

        // 绘制bottom view
        canvas.drawBitmap(getLinearLayoutBitmap(llBottomView, widthBottom, heightBottom), 0,
                (heightTop), paint);

        // 生成最终的文件，并压缩大小，这里使用的是：implementation 'com.github.nanchen2251:CompressHelper:1.0.5'
        try {
            String path = saveBitmapBackPath(bitmapAll, styleType);
            float imageRatio = ImageUtil.getImageRatio(path);
            if (imageRatio >= 10) {
                finalCompressLongPictureWidth = 750;
            } else if (imageRatio >= 5 && imageRatio < 10) {
                finalCompressLongPictureWidth = 900;
            } else {
                finalCompressLongPictureWidth = longPictureWidth;
            }
            Log.d(TAG, "最终生成的长图路径为：" + path);
            if (listener != null) {
                listener.onSuccess(path);
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (listener != null) {
//                listener.onFail();
            }
        }
    }

    public static String saveBitmapBackPath(Bitmap bm, int styleType) throws IOException {
        String path = Environment.getExternalStorageDirectory() + "/hanxiang/temp/";
        File targetDir = new File(path);
        if (!targetDir.exists()) {
            try {
                targetDir.mkdirs();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String fileName = "";
        if (styleType == PosterStyle.POSTER_STYLE_ONE) {
            fileName = "share_poster_one.jpeg";
        } else if (styleType == PosterStyle.POSTER_STYLE_TWO) {
            fileName = "share_poster_two.jpeg";
        } else if (styleType == PosterStyle.POSTER_STYLE_THREE) {
            fileName = "share_poster_three.jpeg";
        }
        File savedFile = new File(path + fileName);
        if (!savedFile.exists()) {
            savedFile.createNewFile();
        }
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(savedFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
        return savedFile.getAbsolutePath();
    }
    public interface Listener {

        /**
         * 生成长图成功的回调
         *
         * @param path 长图路径
         */
        void onSuccess(String path);
    }
}